import router from '@/router'
import {useUserStore} from '@/stores/user'
import type {AxiosRequestConfig} from 'axios'
import axios from 'axios'

export let baseURL: string = 'http://apipc-xiaotuxian-front.itheima.net/'
export let timeout: number = 5000

let axiosInstance = axios.create({
  baseURL,
  timeout
})

// 请求拦截器
axiosInstance.interceptors.request.use(config => {
  let store = useUserStore()
  let token = store.userInfo.token
  // 如果本地存在token，就在header携带
  if (token) {
    config.headers && (config.headers.Authorization = `Bearer ${token}`)
  }
  return config
})

// 响应拦截器
axiosInstance.interceptors.response.use(
  response => response.data,
  err => {
    console.error(err)
    // 响应为401，说明未登录
    if (err.response.status === 401) {
      // 清空无效的用户信息
      let store = useUserStore()
      store.userInfo = {}

      // 跳转到登录页
      router.push({
        path: '/login',
        query: {redirect: router.currentRoute.value.path}
      })
    }
    return err.response.data
  }
)


export default {
  get(url: string, params?: any, config: AxiosRequestConfig = {}) {
    return axiosInstance({
      url,
      method: 'get',
      params,
      ...config
    })
  },
  post(url: string, data?: any, config: AxiosRequestConfig = {}) {
    return axiosInstance({
      url,
      method: 'post',
      data,
      ...config
    })
  },
  put(url: string, data?: any, config: AxiosRequestConfig = {}) {
    return axiosInstance({
      url,
      method: 'put',
      data,
      ...config
    })
  },
  delete(url: string, data?: any, config: AxiosRequestConfig = {}) {
    return axiosInstance({
      url,
      method: 'delete',
      data,
      ...config
    })
  }
}